package com.gitee.androidgoodies.batterylog;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
import android.os.Message;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import java.util.ArrayList;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import android.content.ComponentName;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.SharedPreferences;

public class RecordService extends Service {
    private final static String TAG = "RecordService";
    /*public final static String ACTION_REMOVE_RECORDITEM ="com.androidgoodiez.batterylog.RecordService.ACTION_REMOVE_RECORDITEM";
    public final static String ACTION_ADD_RECORDITEM ="com.androidgoodiez.batterylog.RecordService.ACTION_ADD_RECORDITEM";
    public final static String EXTRA_INT_BATTERY_PERCENTAGE = "EXTRA_INT_BATTERY_PERCENTAGE";    */
    private static final String APP_SPNAME = "RecordService";

    IntentFilter mIntentFilter;
    private ArrayList<RecordItem> mRecordData;
    private static String mszmRecordDataSavePath;
    private boolean mIs_mReceiverRegisted = false;
    public static int mnLineNum = 1;
    public static boolean misLineNumEnable = false;
    private static Context mContext;
    private static RecordServiceReceiver mRecordServiceReceiver;

    @Override
    public IBinder onBind(Intent p1) {
        LogUtils.d(TAG, "onBind");
        return null;
    }


    /** 当服务被创建时调用. */
    @Override
    public void onCreate() {
        LogUtils.d(TAG, "onCreate");
        mContext = this;
        mnLineNum = BatteryLogConfigUtils.getConfigLineNum(this);
        misLineNumEnable = BatteryLogConfigUtils.getConfigIsLineNumEnable(this);


        // 设置存储数据的文件目录
        mszmRecordDataSavePath = getApplicationContext().getExternalFilesDir("data") + "/RecordData.dat";  
        mRecordData = new ArrayList<RecordItem>();
        // 读取旧数据
        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(mszmRecordDataSavePath));
            try {
                mRecordData = (ArrayList<RecordItem>) inputStream.readObject();
            } catch (IOException e) {
                LogUtils.d(TAG, "IOException: " + e.getMessage());
            } catch (ClassNotFoundException e) {
                LogUtils.d(TAG, "ClassNotFoundException: " + e.getMessage());
            }
            inputStream.close();
        } catch (IOException e) {
            LogUtils.d(TAG, "IOException: " + mszmRecordDataSavePath + "|" + e.getMessage());                               
        }

        // 如果没有配置运行,就退出。
        if (BatteryLogConfigUtils.getConfigIsKeepRecordService(RecordService.this)) {

            // 显示所有数据
            //sendBroadcastShowRecordData();
            doReceiverRegisted();
        }
    }

    @Override
    public ComponentName startService(Intent service) {

        return super.startService(service);
    }
    
    private void doReceiverRegisted(){
        // 注册接收系统电量消息  
        if (!mIs_mReceiverRegisted)    {
            mIs_mReceiverRegisted = true;
            mRecordServiceReceiver = new RecordServiceReceiver();
            mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            mIntentFilter.addAction(RecordServiceReceiver.ACTION_REMOVE_RECORDITEM);
            mIntentFilter.addAction(RecordServiceReceiver.ACTION_ADD_RECORDITEM);
            registerReceiver(mRecordServiceReceiver, mIntentFilter);
            
        }
        
    }

    /** 调用startService()启动服务时回调 */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d(TAG, "onStartCommand");
        doReceiverRegisted();
       
        // return 取值参考: https://blog.csdn.net/cyp331203/article/details/38920491
        return START_STICKY;
    }

    /** 服务不再有用且将要被销毁时调用 */
    @Override
    public void onDestroy() {
        LogUtils.d(TAG, "onDestroy");

        if (mIs_mReceiverRegisted) {
            unregisterReceiver(mRecordServiceReceiver); 
        }
    }
    
    public static int getLineNum(){
        return mnLineNum;
    }
    
    public static boolean getIsLineNumEnable(){
        return misLineNumEnable;
    }

    public static void setLineNum(int n){
        mnLineNum = n;
    }
    
    public static void setLineNumEnable(boolean b){
        misLineNumEnable = b;
    }
    
    private void sendBroadcastShowRecordData() {
        //自定义一个action
        Intent intent = new Intent(MainActivity.ACTION_SHOW_RECORDDATA);
        sendBroadcast(intent);
    }

   /*private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int nLevel = intent.getIntExtra("level", 0);
                int nScale = intent.getIntExtra("scale", 100);
                int nBatteryPercentageNow = nLevel * 100 / nScale;
                addRecordItem(nBatteryPercentageNow);

            } else if (ACTION_REMOVE_RECORDITEM.equals(action)) {
                removeAllRecordItem();
            } else if (ACTION_ADD_RECORDITEM.equals(action)) {
                int nBatteryPercentageNow = intent.getIntExtra(EXTRA_INT_BATTERY_PERCENTAGE, 0);
                addRecordItem(nBatteryPercentageNow);
            }
        }
    };*/

    private int getLastBatteryPercentage() {
        int nBatteryPercentage = 0;
        if (mRecordData.size() > 0) {
            nBatteryPercentage = mRecordData.get(mRecordData.size() - 1).mnBatteryPercentage;
        }
        return nBatteryPercentage; 
    }

    private void addRecordItem1(int nBatteryPercentageNow) {
        if (getLastBatteryPercentage() != nBatteryPercentageNow) { 
            // 读取当前时间
            long nTimeNow = System.currentTimeMillis();
            // 加入记录列表
            RecordItem item = new RecordItem(nTimeNow, nBatteryPercentageNow);
            mRecordData.add(item);

            // 限制条数控制
            if (misLineNumEnable&&(mnLineNum > -1)) {
                int nSize = mRecordData.size();
                int nDelete = (nSize < mnLineNum) ? 0: (nSize - mnLineNum);
                for (int i = nDelete - 1; i > -1; i--) {
                    mRecordData.remove(i);
                }
            }

            // 保存到文件
            saveRecordDataToFile();
            sendBroadcastShowRecordData();
        }
    }
    
    public static void addRecordItem2(int nBatteryPercentageNow) {
        if(mContext != null){
        ((RecordService)mContext).addRecordItem1(nBatteryPercentageNow);
        }
    }

    private void saveRecordDataToFile() {
        // 保存记录到文件
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(mszmRecordDataSavePath));
            outputStream.writeObject(mRecordData);
            outputStream.close();
        } catch (IOException e) {
            LogUtils.d(TAG, e.getMessage());
        }
    }

    private void removeAllRecordItem1() { 
        RecordItem item =  mRecordData.get(mRecordData.size() - 1);
        mRecordData.clear();
        item.mnRecordTime = System.currentTimeMillis();
        mRecordData.add(item);
        saveRecordDataToFile();
        sendBroadcastShowRecordData();
    }

    public static void removeAllRecordItem2() { 
        if(mContext != null){
        ((RecordService)mContext).removeAllRecordItem1();
        }
    }

}
